package com.zirenx.common.interceptor;

import java.lang.reflect.Method;

import com.zirenx.utils.R;
import org.apache.shiro.aop.MethodInvocation;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.aop.AnnotationsAuthorizingMethodInterceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;

import javax.servlet.http.HttpServletRequest;

/**
 * Shiro 拦截器
 */
public class ShiroInterceptor extends AnnotationsAuthorizingMethodInterceptor implements Interceptor {

	public ShiroInterceptor() {
		getMethodInterceptors(); // 用来扩展其他注解
	}

	@Override
	public void intercept(final Invocation inv) {
		try {
			invoke(new MethodInvocation() {
				@Override
				public Object proceed() throws Throwable {
					Controller controller = inv.getController();
					//是否异步请求
					if (controller.getRender()==null && isAjax(controller.getRequest())){
						controller.renderJson(R.ok());//设置默认
					}

					inv.invoke();
					return inv.getReturnValue();
				}

				@Override
				public Method getMethod() {
					return inv.getMethod();
				}

				@Override
				public Object[] getArguments() {
					return inv.getArgs();
				}

				@Override
				public Object getThis() {
					return inv.getController();
				}
			});
		} catch (Throwable e) {
			if (e instanceof AuthorizationException) {
				doProcessuUnauthorization(inv.getController());
			}
			System.out.println("权限错误");
			LogKit.warn("权限错误:", e);
		}
	}

	/**
	 * 未授权处理
	 *
	 * @param controller controller
	 */
	private void doProcessuUnauthorization(Controller controller) {
		LogKit.warn("未授权处理");
		controller.renderError(403);
	}

	/**
	 * 是否异步请求
	 * @param request
	 * @return
	 */
	private boolean isAjax(HttpServletRequest request){
		String header = request.getHeader("X-Requested-With");
		if(header!=null && header.equals("XMLHttpRequest")) {
			return true;
		}
		return false;
	}
}